package com.alex.server.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT登陆授权过滤器
 * 先判断token存不存在,如果存在,从token头部中,截取token,再根据token获取用户名,
 * 如果能够得到用户名,还有判断spring security的全局变量中,是否含有用户对象,如果没有
 * 代表token存在,但是未登录
 */
public class JwtAuthencationTokenFilter extends OncePerRequestFilter {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtTokenUtils jwtTokenUtils;
    @Autowired
    private UserDetailsService userDetailsService;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String header = httpServletRequest.getHeader(tokenHeader);
        //头部不存在,或者存在但是不是以tokenHead开头
        if (null!=header&&header.startsWith(tokenHead)){
            String authToken = header.substring(tokenHead.length());
            String name = jwtTokenUtils.getUserNameFromToken(authToken);
            //能拿到用户名,但是在spring security全局上下文中拿不到我们的用户对象,也就是说token存在,但是未登录
            if (null!=name && null== SecurityContextHolder.getContext().getAuthentication()){
                //登录
                UserDetails userDetails = userDetailsService.loadUserByUsername(name);
                //验证token是否有效,重新设置用户对象
                if(jwtTokenUtils.validateToken(authToken,userDetails)){
                    //在spring security全局变量中,将其用户名和密码以及权限加进去
                    UsernamePasswordAuthenticationToken authenticationToken= new
                            UsernamePasswordAuthenticationToken(userDetails,null, userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
